package com.hsnn.medstgmini.base.dict.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicCompTypeLogDao;
import com.hsnn.medstgmini.base.dict.model.DicCompTypeLog;
import com.hsnn.medstgmini.model.Result;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;

@SuppressWarnings("deprecation")
@Repository
public class DicCompTypeLogDaoImpl implements DicCompTypeLogDao {

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public List<DicCompTypeLog> dicCompTypeLogList(Result result, DicCompTypeLog dicCompTypeLog) {
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from "
				+ "DicCompTypeLog d2, DicCompType d1 "
				+ "where d2.fatherId = d1.compRegId and d2.compRegId = :compRegId ");
		
		
		String start = dicCompTypeLog.getStartTime();
		String end = dicCompTypeLog.getEndTime();
		if (start != null && StringUtils.isNotEmpty(start)) {
			sb.append("and d1.updDatetime >= :startTime ");
		}
		if (end != null && StringUtils.isNotEmpty(end)) {
			sb.append("and d1.updDatetime <= :endTime ");
		}
		Query query = session.createQuery(sb.toString());
		query.setString("compRegId", dicCompTypeLog.getCompRegId());
		
		
		if (start != null && StringUtils.isNotEmpty(start)) {
			query.setTimestamp("startTime", DateUtil.parseDateTime(start));
		}
		if (end != null && StringUtils.isNotEmpty(end)) {
			query.setTimestamp("endTime", DateUtil.parseDateTime(end));
		}
		
		Long total = (Long) query.uniqueResult();
		result.setRecords(total);
		
		//查询分页数据
		sb.setLength(0);
		//sb.append("select d1.* from DicCompTypeLog d1, DicCompType d2 where d1.compRegId = d2.compRegId and d1.compRegId = :compRegId ");
		sb.append("select new DicCompTypeLog (");
		sb.append("d2.compRegId, ");
		sb.append("d2.compRegCode, ");
		sb.append("d2.compRegName, ");
		sb.append("d2.fatherId, ");
		sb.append("d2.remark, ");
		sb.append("d2.status, ");
		sb.append("d2.updDatetime, ");
		sb.append("d2.updUser, ");
		sb.append("d2.sortId, ");
		sb.append("d1.compRegCode as fatherCompRegCode, ");
		sb.append("d1.compRegName as fatherCompRegName ) ");
		sb.append("from DicCompTypeLog as d2, DicCompType as d1 ");
		sb.append("where d1.compRegId = d2.fatherId and d2.compRegId = :compRegId ");
			
		
		if (start != null && StringUtils.isNotEmpty(start)) {
			sb.append(" and d1.updDatetime >= :startTime ");
		}
		if (end != null && StringUtils.isNotEmpty(end)) {
			sb.append(" and d1.updDatetime <= :endTime ");
		}
		sb.append(" order by d1.updDatetime desc");
		
		query = session.createQuery(sb.toString());
		
		query.setString("compRegId", dicCompTypeLog.getCompRegId());
		
		if (start != null && StringUtils.isNotEmpty(start)) {
			query.setTimestamp("startTime", DateUtil.parseDateTime(start));
		}
		if (end != null && StringUtils.isNotEmpty(end)) {
			query.setTimestamp("endTime", DateUtil.parseDateTime(end));
		}
		
		query.setFirstResult(result.getStart());
		query.setMaxResults(result.getPagesize());
		return query.list();
	}
	
	@Override
	public Pagination getDicCompTypeLogList(Pagination page){
		Session session = sessionFactory.getCurrentSession();
		String startTime = page.getConditions().get("startTime");
		String endTime = page.getConditions().get("endTime");
		String compRegId = page.getConditions().get("compRegId");
		String compRegCode =page.getConditions().get("compRegCode");
		StringBuffer sql1 = new StringBuffer();
		sql1.append("	    SELECT sql_calc_found_rows a.comp_reg_code fatherCompRegCode,a.comp_reg_name fatherCompRegName,NULL compRegCode,NULL compRegName,a.status status,    ")
			.append("		s.name updUser,a.upd_datetime updDatetime,a.log_id logId,a.detail FROM  dic_comptype_log a       ")
			.append("	     LEFT JOIN sys_user s ON s.id=a.upd_user              						 ")
			.append("       WHERE a.comp_reg_id=:compRegId                                				 ");
		StringBuffer sql2 = new StringBuffer();
		sql2.append("SELECT sql_calc_found_rows a.comp_reg_code fatherCompRegCode,a.comp_reg_name fatherCompRegName,b.comp_reg_code compRegCode,b.comp_reg_name compRegName,     ")
		    .append(" b.status status,s.name updUser,b.upd_datetime updDatetime,b.log_id logId,b.detail  FROM  dic_comptype_log b  ")
		    .append(" INNER JOIN dic_comptype a ON a.comp_reg_id=b.father_id         					  ")
		    .append(" LEFT JOIN sys_user s ON s.id=b.upd_user                     							  ")
		    .append(" WHERE b.comp_reg_id=:compRegId                                     					  ");
		if(StringUtils.isNotBlank(compRegCode)){
			if(StringUtils.isNotBlank(startTime)){
				sql2.append(" and b.upd_datetime >= :startTime ");
			}
			if(StringUtils.isNotBlank(endTime)){
				sql2.append(" and b.upd_datetime <= :endTime ");
			}
			sql2.append(" order by b.upd_datetime desc");
			Query query = session.createSQLQuery(sql2.toString());
			Query queryCount = session.createSQLQuery("select found_rows() ");
			query.setString("compRegId", compRegId);
			if(StringUtils.isNotBlank(startTime)){
				query.setString("startTime", startTime+" 00:00:00");
			}
			if(StringUtils.isNotBlank(endTime)){
				query.setString("endTime", endTime+" 23:59:59");
			}
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getMaxResults());
			query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			page.setRows(query.list());
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			return page;
		}else{
			if(StringUtils.isNotBlank(startTime)){
				sql1.append(" and a.upd_datetime >= :startTime ");
			}
			if(StringUtils.isNotBlank(endTime)){
				sql1.append(" and a.upd_datetime <= :endTime ");
			}
			sql1.append(" order by a.upd_datetime desc");
			Query query = session.createSQLQuery(sql1.toString());
			Query queryCount = session.createSQLQuery("select found_rows() ");
			query.setString("compRegId", compRegId);
			if(StringUtils.isNotBlank(startTime)){
				query.setString("startTime", startTime+" 00:00:00");
			}
			if(StringUtils.isNotBlank(endTime)){
				query.setString("endTime", endTime+" 23:59:59");
			}
			query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			return page;
		}
	}

	/**
	 * 基础库 数据字典 企业注册类型维护记录 日志详情
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getDicCompTypeLogDetail(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String logId = page.getConditions().get("logId");
		StringBuffer  sql = new StringBuffer();
		sql.append(" SELECT     case when b.father_id = '0' then b.comp_reg_code else a.comp_reg_code end fatherCompRegCode,   ")
		   .append(" case when b.father_id = '0' then b.comp_reg_name else a.comp_reg_name end fatherCompRegName,  ")
		   .append(" case when b.father_id = '0' then null else b.comp_reg_code end compRegCode, ")
		   .append(" case when b.father_id = '0' then null else b.comp_reg_name end compRegName ,  b.status status,s.name updUser,date_format(b.upd_datetime,'%Y-%m-%d %H:%i:%S') updDatetime  ")
		   .append(" FROM  dic_comptype_log b  LEFT JOIN dic_comptype a ON a.comp_reg_id=b.father_id LEFT JOIN sys_user s ON s.id=b.upd_user ")
		   .append(" WHERE b.comp_reg_id = (SELECT comp_reg_id FROM dic_comptype_log WHERE log_id = :logId)    ")
		   .append(" AND b.upd_datetime <= (SELECT upd_datetime FROM dic_comptype_log where log_id = :logId)  ")
		   .append(" order by b.upd_datetime desc limit 2 ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("logId", logId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}
	
	
	

}
